package com.spzx.product.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类Service业务层处理
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> treeSelect(Long parentId) {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(item -> {
                //todo 需优化
                long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, item.getId()));
                if (count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    @Override
    public List<Long> getAllCategoryIdList(Long categoryId) {
        ArrayList<Long> categoryIdList = new ArrayList<>();
        List<Category> categoryList = this.getParentCategory(categoryId,new ArrayList<Category>());
        int size = categoryList.size();
        for (int i = 0; i < size; i++) {
            categoryIdList.add(categoryList.get(i).getId());
        }
        return categoryIdList;
    }

    private List<Category> getParentCategory(Long categoryId, ArrayList<Category> categories) {
        while (categoryId > 0){
            Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getId, categoryId));
            categories.add(category);
            return getParentCategory(category.getParentId(),categories);
        }
        return categories;
    }


}